/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

#if _LOCALDB
  namespace Oceanside.LocalDB
#else
namespace Oceanside.RemoteDB
#endif
{
    public partial class PCILOG
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bindExpr"></param>
        /// <param name="mode"></param>
        public static void LogToSysLog(EntityObject obj, string mode)
        {
            if (obj != null && obj.EntityKey != null && obj.EntityKey.EntityKeyValues != null && obj.EntityKey.EntityKeyValues.Count() != 0)
            {
                string description = "BOH: " + mode + " " + obj.EntityKey.EntitySetName;
                description += " where Id = " + obj.EntityKey.EntityKeyValues.First().Value;

                if (SHIFT.Current != null &&
                    SHIFT.Current.User != null)
                {
                    StartLogEntryThread(SHIFT.Current.User.Id, description);
                }
                else
                {
                    StartLogEntryThread(Int64.MaxValue, description);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bindExpr"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public static void LogToSysLog(BindingExpression bindExpr, object from, object to)
        {
            if (bindExpr != null)
            {
                EntityObject obj = bindExpr.DataItem as EntityObject;

                if (obj != null && bindExpr.ParentBinding != null)
                {
                    PropertyPath path = bindExpr.ParentBinding.Path;

                    string description = "BOH: Edit " + obj.EntityKey.EntitySetName;
                    description += "." + path.Path + " from " + from + " to " + to;
                    description += " where Id = " + obj.EntityKey.EntityKeyValues.First().Value;

                    if (SHIFT.Current != null &&
                        SHIFT.Current.User != null)
                    {
                        StartLogEntryThread(SHIFT.Current.User.Id, description);
                    }
                    else
                    {
                        StartLogEntryThread(Int64.MaxValue, description);
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="action"></param>
        public static void StartLogEntryThread(Int64 userId, string action)
        {
            Task.Factory.StartNew(() => LogEntry_NOTHROW(userId, action));
        }

        /// <summary>
        /// Prevents duplicate entries.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private static bool HasDuplicate(DominicaEntities context, string action)
        {
            PCILOG lastLog = context.PCILOGS.OrderByDescending(x => x.DateStamp).FirstOrDefault();
            if (lastLog == null || lastLog.Action == null || !lastLog.Action.Equals(action))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="action"></param>
        private static void LogEntry_NOTHROW(Int64 userId, string action)
        {
            try
            {
                using (DominicaEntities sysLogContext =
                    new DominicaEntities(DominicaEntities.GetEfConString()))
                {
                    if (!HasDuplicate(sysLogContext, action))
                    {
                        PCILOG access = new PCILOG();
                        access.DateStamp = DateTime.Now;
                        access.Action = action;
                        access.UserId = userId;
                        sysLogContext.PCILOGS.AddObject(access);
                        sysLogContext.SaveChanges();
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SYSLOG_LOGENTRY, exc);
            }
        }
    }
}
